$(function() {
	//视图构建顺序：this.cid -> _.extend(this, _.pick(options, viewOptions)) el,events等的完善
	// -> this._ensureElement() -> this.initialize

	//events绑定利用的是jquery的on，so即使元素还在模板里没有渲染到dom中，
	//在渲染后，也会绑定事件
	var Good = Backbone.Model.extend({
		defaults: function() {
			return {
				// id: Goods.nextId(),
				id: 0,
				price: 30,
				number: 1,
				checked: false
			};
		}
	});

	var GoodList = Backbone.Collection.extend({
		model: Good,
		localStorage: new Backbone.LocalStorage("shopcar-backbone"),

		selected: function() {
			return this.where({checked: true});
		},
		nextId: function() {
			return this.length ? this.length + 1 : 1;
		}
	});

	var Goods = new GoodList();

	var GoodView = Backbone.View.extend({
		tagName: 'div',
		attributes: {class: 'row sc-shirt'},

		template: _.template($('#good-template').html()),

		events: {//imp:事件委托?
			'click .sc-check-real': 'toggleCheck',
			'click .sc-minus': 'reduceNum',
			'click .sc-plus': 'addNum',
			'keyup .sc-num-input': 'validNum',
			'click .sc-op': 'deleteGood'
		},

		initialize: function() {
			this.listenTo(this.model, 'change', this.render);
			this.listenTo(this.model, 'destroy', this.remove);
		},
		render: function() {
			this.$el.html(this.template(this.model.toJSON()));
			if (this.model.get('number') === 1) {
				this.$('.sc-minus').addClass('op-disable');
			} else {
				this.$('.sc-minus').removeClass('op-disable');
			}
			this.$input = this.$el.find('.sc-num-input');
			return this;
		},

		toggleCheck: function() {
			this.model.set('checked', !this.model.get('checked'));
		},
		reduceNum: function() {
			this.model.set('number', parseInt(this.model.get('number')) - 1);
		},
		addNum: function() {
			this.model.set('number', parseInt(this.model.get('number')) + 1);
		},
		validNum: function(event) {
			var e = event || window.event,
				key = e.keyCode;
			if (!((key > 47 && key < 58) || key === 8 || (key > 95 && key < 106))) {
				e.preventDefault ? e.preventDefault() : (e.returnValue = false);
			}
			this.$input.val() ? this.$input.val() : this.$input.val(1);
			this.changeNumber();
			//question: this.$input会失焦
		},
		changeNumber: function() {
			this.model.set('number', parseInt(this.$input.val()));
		},
		deleteGood: function() {
			this.model.destroy();
		}
	});

	var AppView = Backbone.View.extend({
		el: $('#sc-app'),
		statsTemplate: _.template($('#app-template').html()),

		events: {
			'click .allCheck': 'checkAll',
			'click .sc-deleteAll': 'deleteGoods'
		},

		initialize: function() {
			this.listenTo(Goods, 'add', this.addOne);
			this.listenTo(Goods, 'reset', this.addAll);
			this.listenTo(Goods, 'all', this.render);

			this.$shirts = $('.sc-shirts');
			this.$bottom = $('.sc-bottom');
			this.allChecked = false;

			Goods.fetch();
		},
		render: function() {
			var checkeds = Goods.selected(),
				num = checkeds.length,
				total = 0,
				disabled = checkeds.length ? false : true;
			/*total = _.reduce(Goods, function(pre, cur) {
				return pre + cur.get('number') * cur.get('price');
			}, 0);*/
			checkeds.forEach(function(good) {
				total += good.get('number') * good.get('price');
			});
			this.$bottom.html(this.statsTemplate({checkeds: num, total: total, disable: disabled}));
			return this;
		},

		addOne: function(m) {
			var view = new GoodView({model: m});
			this.$shirts.append(view.render().el);
		},
		addAll: function(goods) {
			goods.forEach(function(good) {
				this.addOne(good);
			}.bind(this));
		},
		checkAll: function() {
			var allChecked = !this.allChecked;
			this.allChecked = !this.allChecked;
			$('.allCheck').prop('checked', this.allChecked);
			Goods.forEach(function(good) {
				//get:再一次认识到this的随意，切记要判断this的指向
				// good.set('checked', this.allChecked);
				good.set('checked', allChecked);
			});
		},
		deleteGoods: function() {
			var checkeds = Goods.selected();
			checkeds.forEach(function(good) {
				good.destroy();
			});
		}
	});

	var App = new AppView();

	Goods.reset([{id: 1}, {id: 2}, {id: 3}]);
});